package com.example.javabase.java8;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.LongStream;

/**
 * @author haitao
 * @date 2021/10/13 9:55 上午
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Apple {

    private String color;

    private Integer weight;

    public static boolean isGreenApple(Apple apple) {
        return "green".equals(apple.getColor());
    }

    public static boolean isHeavyApple(Apple apple) {
        return apple.getWeight() > 150;
    }

    static List<Apple> filterApples(List<Apple> inventory,
                                    Predicate<Apple> p) {
        List<Apple> result = new ArrayList<>();
        for (Apple apple : inventory) {
            if (p.test(apple)) {
                result.add(apple);
            }
        }
        return result;
    }
    // 业务处理

    static void filterGreenApple() {
        List<Apple> inventory = Collections.singletonList(new Apple("red", 160));
        List<Apple> filterApples = filterApples(inventory, Apple::isGreenApple);
        System.out.println(filterApples);
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public Integer getWeight(int temp) {
        return weight;
    }

    public void setWeight(Integer weight) {
        this.weight = weight;
    }

    /**
     * lambda 访问局部变量的限制
     */
    static void lambdaAccessingLocalVariables() {
        Apple apple = new Apple();
        final int portNumber = 1337;
        Runnable r = () -> {
            apple.setColor("green");
            System.out.println(portNumber);
        };
        r.run();
        apple.setWeight(1);
    }


    public static long rangedSum(long n) {
        return LongStream.rangeClosed(1, n)
                .reduce(0L, Long::sum);
    }

    public static long sideEffectParallelSum(long n) {
        Accumulator accumulator = new Accumulator();
        LongStream.rangeClosed(1, n).parallel().forEach(accumulator::add);
        return accumulator.total;
    }
    public static class Accumulator {
        public long total = 0;
        public void add(long value) { total += value; }
    }

    public static void main(String[] args) {
        System.out.println(sideEffectParallelSum(100));
    }
}
